package hibari.server.lib;

import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;

import javax.servlet.http.HttpSession;

public class AdminLog implements Serializable {
    private static final String SESSION_KEY = "admin-log";
    private static final long serialVersionUID = -2526091934408660963L;

    public static AdminLog get(HttpSession session) {
        AdminLog result = (AdminLog) session.getAttribute(SESSION_KEY);
        if (result == null) {
            result = new AdminLog();
            session.setAttribute(SESSION_KEY, result);
        }
        return result;
    }

    public static AdminLog get(MultiPartRequest request) {
        return get(request.getPlainRequest().getSession());
    }

    private ArrayList<AdminLogItem> messages;

    public AdminLog() {
        this.messages = new ArrayList<AdminLogItem>();
    }

    public void add(AdminLogItem message) {
        this.messages.add(message);
    }

    public void addError(String error) {
        add(new AdminLogItem(AdminLogItem.KIND_ERROR, error));
    }

    public void addInfo(String info) {
        add(new AdminLogItem(info));
    }

    public void update(HttpSession session) {
        session.setAttribute(SESSION_KEY, this);
    }

    public String render(HttpSession session) {
        if (this.messages.size() == 0) {
            return "";
        }

        StringWriter writer = new StringWriter();

        try {
            writer.write("<ul id=\"message-box\">");
            for (AdminLogItem each : this.messages) {
                writer.write(each.render());
            }
            writer.write("</ul>");
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.messages.clear();

        update(session);
        return writer.toString();
    }
}
